import java.util.ArrayList;
import java.util.List;

public class Router {
    private List<Route> routes = new ArrayList<Route>();

    public Router(Iterable<Route> routes) {
        for ( Route route : routes ) {
            this.routes.add(route);
        }
    }

    void addRoute(Route route) {
        this.routes.add(route);
    }

    Route getRouteForAddress(String address) throws InvalidIpAddressException {
        Route bestRoute = null;
        int maxMaskLength = -1;
        int maxMetric = -1;

        for ( Route route : this.routes) {
            Network net = route.getNetwork();

            if ( net.contains(address) ) {
                if ((net.getMaskLength() > maxMaskLength) || ((net.getMaskLength() == maxMaskLength) && (route.getMetric() > maxMetric))) {
                    bestRoute = route;
                    maxMaskLength = net.getMaskLength();
                    maxMetric = route.getMetric();
                }
            }
        }
        return bestRoute;
    }

    Iterable<Route> getRoutes() {
        return this.routes;
    }

    void removeRoute(Route route) {
        this.routes.remove(route);
    }
}
